#!/usr/bin/env python
import sys
import curses
from html3 import htmldom, style, agent, device, layout
from curspad import get_unicode, CursPad

def CTRL(x): return ord(x) & 0x1f


##  Browser
##
class Browser(object):
  
  def __init__(self, window, size, codec='euc-jp', default_charset='euc-jp'):
    window.keypad(1)
    self.window = window
    self.size = size
    self.codec = codec
    self.default_charset = default_charset
    (width, height) = size
    self.device = device.JPCursesDevice(width, height, window, codec)
    self.agent = agent.Agent()
    self.stylesheet = style.ActiveStyleSheet(device=self.device, agent=self.agent)
    self.stylesheet.parse_lines([
      u'a { font: link }\n',
      u'ul { text-indent: 2em; }\n',
      u'hr { width: 100%; margin-top: 1em; margin-bottom: 1em; }\n',
      u'table { table-border: 1em; }\n',
      u'p,center,h1,h2,h3,h4,h5,h6,hr,ul { para-space: 1em; }\n',
      ])
    self.frame = None
    self.status_y = height
    self.status = ''
    curses.init_pair(10, curses.COLOR_BLACK, curses.COLOR_GREEN)
    return
  
  def visit(self, url):
    stylesheet = self.stylesheet.dup()
    stylesheet.set_base(url)
    (fp, content_type, charset) = self.agent.get(url)
    charset = charset or self.default_charset
    root = htmldom.parse_html(fp, base_href=url, charset=charset,
                              stylesheet=stylesheet)
    fp.close()
    self.frame = layout.Frame(self.device, root, self.device.width, stylesheet)
    self.frame.build()
    self.redraw()
    return

  def focus_prev(self):
    self.frame.change_focus(-1)
    self.redraw()
    return True

  def focus_next(self):
    self.frame.change_focus(1)
    self.redraw()
    return True

  def activate(self):
    return False

  def quit(self):
    return False

  def redraw(self):
    self.frame.render(0, 0)
    self.device.paint()
    self.window.addstr(self.status_y, 0, self.status, curses.color_pair(10))
    return

  def feed(self, c):
    loop = True
    try:
      loop = (self.KEYMAP[c])(self)
    except KeyError:
      pass
    self.status = 'key:%r' % c
    self.redraw()
    return loop

  def mainloop(self):
    while self.feed(get_unicode(self.window, self.codec)):
      pass
    return

  KEYMAP = {
    curses.KEY_UP: focus_prev,
    curses.KEY_DOWN: focus_next,
    'k': focus_prev,
    'j': focus_next,
    'q': quit,
    'Q': quit,
    27: quit,
    10: activate,
    }
  

# main
def main(stdscr):
  argv = sys.argv
  args = argv[1:]
  #
  start_url = args[0]
  browser = Browser(stdscr, (60,20))
  browser.visit(start_url)
  browser.mainloop()
  return

if __name__ == '__main__': curses.wrapper(main)
